package com.example.service;

import com.example.api.CustomApi;
import com.example.api.UserApi;
import com.example.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 用户服务类
 * 演示如何使用 Retrofit API 接口
 * 
 * @author example
 * @since 2024-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserApi userApi;
    private final CustomApi customApi;

    /**
     * 获取所有用户
     */
    public List<User> getAllUsers() {
        try {
            Call<List<User>> call = userApi.getUsers();
            Response<List<User>> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功获取用户列表，数量: {}", response.body().size());
                return response.body();
            } else {
                log.error("获取用户列表失败，状态码: {}", response.code());
                return List.of();
            }
        } catch (IOException e) {
            log.error("获取用户列表异常", e);
            return List.of();
        }
    }

    /**
     * 根据 ID 获取用户
     */
    public User getUserById(Long id) {
        try {
            Call<User> call = userApi.getUser(id);
            Response<User> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功获取用户信息: {}", response.body().getName());
                return response.body();
            } else {
                log.error("获取用户信息失败，用户ID: {}, 状态码: {}", id, response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("获取用户信息异常，用户ID: {}", id, e);
            return null;
        }
    }

    /**
     * 异步获取用户
     */
    public User getUserByIdAsync(Long id) {
        try {
            CompletableFuture<User> future = userApi.getUserAsync(id);
            User user = future.get();
            log.info("异步获取用户信息成功: {}", user.getName());
            return user;
        } catch (InterruptedException | ExecutionException e) {
            log.error("异步获取用户信息异常，用户ID: {}", id, e);
            return null;
        }
    }

    /**
     * 创建用户
     */
    public User createUser(User user) {
        try {
            Call<User> call = userApi.createUser(user);
            Response<User> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功创建用户: {}", response.body().getName());
                return response.body();
            } else {
                log.error("创建用户失败，状态码: {}", response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("创建用户异常", e);
            return null;
        }
    }

    /**
     * 更新用户
     */
    public User updateUser(Long id, User user) {
        try {
            Call<User> call = userApi.updateUser(id, user);
            Response<User> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功更新用户: {}", response.body().getName());
                return response.body();
            } else {
                log.error("更新用户失败，用户ID: {}, 状态码: {}", id, response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("更新用户异常，用户ID: {}", id, e);
            return null;
        }
    }

    /**
     * 删除用户
     */
    public boolean deleteUser(Long id) {
        try {
            Call<Void> call = userApi.deleteUser(id);
            Response<Void> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功删除用户，用户ID: {}", id);
                return true;
            } else {
                log.error("删除用户失败，用户ID: {}, 状态码: {}", id, response.code());
                return false;
            }
        } catch (IOException e) {
            log.error("删除用户异常，用户ID: {}", id, e);
            return false;
        }
    }

    /**
     * 搜索用户
     */
    public List<User> searchUsers(String name, String email) {
        try {
            Call<List<User>> call = userApi.searchUsers(name, email);
            Response<List<User>> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("搜索用户成功，结果数量: {}", response.body().size());
                return response.body();
            } else {
                log.error("搜索用户失败，状态码: {}", response.code());
                return List.of();
            }
        } catch (IOException e) {
            log.error("搜索用户异常", e);
            return List.of();
        }
    }

    /**
     * 使用 Map 参数搜索用户
     */
    public List<User> searchUsersWithMap(Map<String, Object> params) {
        try {
            Call<List<User>> call = userApi.searchUsersWithMap(params);
            Response<List<User>> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("使用Map参数搜索用户成功，结果数量: {}", response.body().size());
                return response.body();
            } else {
                log.error("使用Map参数搜索用户失败，状态码: {}", response.code());
                return List.of();
            }
        } catch (IOException e) {
            log.error("使用Map参数搜索用户异常", e);
            return List.of();
        }
    }

    /**
     * 带认证的获取用户
     */
    public User getUserWithAuth(Long id, String token) {
        try {
            Call<User> call = userApi.getUserWithAuth("Bearer " + token, id);
            Response<User> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("带认证获取用户信息成功: {}", response.body().getName());
                return response.body();
            } else {
                log.error("带认证获取用户信息失败，用户ID: {}, 状态码: {}", id, response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("带认证获取用户信息异常，用户ID: {}", id, e);
            return null;
        }
    }

    /**
     * 带重试机制的获取用户
     */
    public User getUserWithRetry(Long id) {
        try {
            Call<User> call = userApi.getUserWithRetry(id);
            Response<User> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("带重试机制获取用户信息成功: {}", response.body().getName());
                return response.body();
            } else {
                log.error("带重试机制获取用户信息失败，用户ID: {}, 状态码: {}", id, response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("带重试机制获取用户信息异常，用户ID: {}", id, e);
            return null;
        }
    }

    /**
     * 使用自定义 API（带签名）获取用户
     */
    public List<User> getUsersWithSign() {
        try {
            Call<List<User>> call = customApi.getUsersWithSign();
            Response<List<User>> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("带签名获取用户列表成功，数量: {}", response.body().size());
                return response.body();
            } else {
                log.error("带签名获取用户列表失败，状态码: {}", response.code());
                return List.of();
            }
        } catch (IOException e) {
            log.error("带签名获取用户列表异常", e);
            return List.of();
        }
    }

    /**
     * 使用自定义 API（带签名）根据 ID 获取用户
     */
    public User getUserWithSign(Long id) {
        try {
            Call<User> call = customApi.getUserWithSign(id);
            Response<User> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("带签名获取用户信息成功: {}", response.body().getName());
                return response.body();
            } else {
                log.error("带签名获取用户信息失败，用户ID: {}, 状态码: {}", id, response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("带签名获取用户信息异常，用户ID: {}", id, e);
            return null;
        }
    }

    /**
     * 演示各种搜索参数的用法
     */
    public void demonstrateSearchFeatures() {
        log.info("=== 演示搜索功能 ===");
        
        // 1. 基本搜索
        searchUsers("Leanne Graham", null);
        
        // 2. 使用 Map 参数搜索
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("name", "Leanne Graham");
        searchParams.put("username", "Bret");
        searchUsersWithMap(searchParams);
        
        log.info("=== 搜索功能演示完成 ===");
    }
} 